package cn.edu.sdyu.ie.crs.service.impl;

import cn.edu.sdyu.ie.crs.domain.Classroom;
import cn.edu.sdyu.ie.crs.domain.ClassroomBuilding;
import cn.edu.sdyu.ie.crs.repository.ClassroomBuildingRepository;
import cn.edu.sdyu.ie.crs.repository.ClassroomRepository;
import cn.edu.sdyu.ie.crs.service.ClassroomBuildingService;
import cn.edu.sdyu.ie.crs.service.ClassroomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class ClassroomBuildingServiceImpl implements ClassroomBuildingService {

    @Autowired
    private ClassroomBuildingRepository classroomBuildingRepository;

    @Override
    public List<ClassroomBuilding> findAll() {
        return classroomBuildingRepository.findAll();
    }

    @Override
    public Page<ClassroomBuilding> findByPage(Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page, pageSize, Sort.by(Sort.Direction.DESC,"id"));
        return classroomBuildingRepository.findAll(pageable);
    }

    @Override
    public ClassroomBuilding findClassroomBuildingById(Integer id) {
        Optional<ClassroomBuilding> optional = classroomBuildingRepository.findById(id);
        if(optional.isPresent()) {
            return optional.get();
        } else {
            log.warn("指定教学楼信息[ID:{}]不存在", id);
            return null;
        }

        // return classroomBuildingRepository.findById(id).orElse(null);
    }

    @Override
    public void saveClassroomBuilding(ClassroomBuilding classroomBuilding) {
        if(classroomBuilding.getId() == null) {
            classroomBuilding.setCreateTime(new Date());
        }
        classroomBuildingRepository.save(classroomBuilding);
    }

    @Override
    public void deleteClassroomBuildingById(Integer id) {
        classroomBuildingRepository.deleteById(id);
    }
}